//
//  CaptureTableViewController.m
//  DoorBell
//
//  Created by Eques-imac on 2017/7/20.
//  Copyright © 2017年 Eques-imac. All rights reserved.
//
#import "CatCapTableViewController.h"
#import "YKSettingDetailModle.h"
#import "SettingDetailTableViewCell.h"
@interface CatCapTableViewController ()
{
    BOOL isOpen;
    BOOL isOpenVideo;
    BOOL customFlag;
    BOOL cancelpost;
    FBDevicesList *devicesinfo;
    NSIndexPath *selectedIndex;
    UIButton *saveBtn;
    BOOL open_status;
}

@end


static NSString *cellname = @"SettingDetailTableViewCell";
@implementation CatCapTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     customFlag = NO;
    
    
    
    [self backBtn];
}
- (void)backBtn{


    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.frame = CGRectMake(0,0,80,40);
    backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
    backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
    [backbtn setImage: [UIImage imageNamed:@"button_back_lightgray_arrow"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftAction) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
    
    
    devicesinfo =  [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    
    saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, 0,80, 20);
   [saveBtn setTitle:NSLocalizedString(@"保存", nil) forState:UIControlStateNormal];
   [saveBtn addTarget:self action:@selector(saveToneAction:) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.titleLabel.font  = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
   [saveBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
   UIBarButtonItem *saveBarButton = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
   self.navigationItem.rightBarButtonItem = saveBarButton;

    
    
    if(devicesinfo.alm_mod == 1){
        _PhotoOrCapture = NSLocalizedString(@"抓拍", nil);
    }else{
         isOpen = YES;
        _PhotoOrCapture = NSLocalizedString(@"录像", nil);
    }
    
    if(devicesinfo.video_time == 5){
        _videotime = NSLocalizedString(@"5 秒", nil);
    }else if ( devicesinfo.video_time == 10){
        _videotime = NSLocalizedString(@"10 秒", nil);
    }else{
        _videotime = NSLocalizedString(@"15 秒", nil);
    }
    
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     settingBtn.frame = CGRectMake(0, 0,80, 44);
    [settingBtn setTitle:NSLocalizedString(@"智能侦测", nil) forState:UIControlStateNormal];
    [settingBtn setTitleColor:[HexChangeRGB colorWithHexString:@"#754c24"] forState:UIControlStateNormal];
     settingBtn.titleLabel.font =[UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
     self.navigationItem.titleView = settingBtn;
     self.tableView.backgroundColor = [HexChangeRGB colorWithHexString:@"#f5f5f5"];
     self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 50;
    [self.tableView registerClass:[SettingDetailTableViewCell class] forCellReuseIdentifier:cellname];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    } else {
    }
    
    
    [self reloadData:devicesinfo.alarm_enable];
   
}


- (void)reloadData:(BOOL)is_open
{
     open_status = is_open;
    [self.modelArrary removeAllObjects];
    
    YKSettingDetailModle *cellData1_0 = [[YKSettingDetailModle alloc] init];
    cellData1_0.title = NSLocalizedString(@"喂食抓拍或录像", nil);
    cellData1_0.detailTitle = NSLocalizedString(@"喂食抓拍或录像", nil);
    cellData1_0.isHaveSwitch = YES;
    cellData1_0.openStatus = open_status;
    NSArray *groupArray1_0 = [NSArray arrayWithObjects:cellData1_0, nil];
    
    
     YKSettingDetailModle *cellData1 = [[YKSettingDetailModle alloc] init];
     cellData1.title = NSLocalizedString(@"抓拍", nil);
     cellData1.detailTitle= NSLocalizedString(@"默认抓拍一张", nil);
     NSArray *groupArray1 = [NSArray arrayWithObjects:cellData1, nil];
    
    YKSettingDetailModle *cellData5 = [[YKSettingDetailModle alloc] init];
    cellData5.title = NSLocalizedString(@"录像", nil);
    cellData5.detailTitle = NSLocalizedString(@"可选择5,10,15秒", nil);
    
    NSArray *groupArray3 = [NSArray arrayWithObjects:cellData5, nil];

    
    YKSettingDetailModle *cellData6 = [[YKSettingDetailModle alloc] init];
    cellData6.title = NSLocalizedString(@"5 秒", nil);
    YKSettingDetailModle *cellData7 = [[YKSettingDetailModle alloc] init];
    cellData7.title = NSLocalizedString(@"10 秒", nil);
    YKSettingDetailModle *cellData8 = [[YKSettingDetailModle alloc] init];
    cellData8.title = NSLocalizedString(@"15 秒", nil);
    NSArray *groupArray4 = [NSArray arrayWithObjects:cellData6,cellData7,cellData8,nil];
    
    self.modelArrary = [NSMutableArray arrayWithObjects:groupArray1_0,groupArray1,groupArray3,groupArray4,nil];
    
    [self.tableView reloadData];
}

- (void)wake_up_t1_r700_result:(NSNotification*)notification
{
    NSDictionary *dict = (NSDictionary*)notification.object;
    NSString *bid =  [dict objectForKey:@"from"];
    if ([self.bid isEqualToString:bid]) {
        cancelpost = YES;
    }
}



- (void)selectLeftAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self tableView:self.tableView viewForHeaderInSection:1];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if (open_status) {
        return  self.modelArrary.count;
    }else{
        return  1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    NSInteger sectionNumber = 0;
    switch (section) {
        case 0:
            sectionNumber = 1;
            break;
            
        case 1:
            sectionNumber = 1;
            break;
        case 2:
        {
            sectionNumber = 1;
        }
            break;
        case 3:
            if (isOpen) { // 打开cell返回数组的count
                sectionNumber = 3;
            }else{
                sectionNumber = 0;
            }
          break;

        default:
            break;
    }
    return sectionNumber;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

      SettingDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellname forIndexPath:indexPath];
    
      NSArray *array = self.modelArrary[indexPath.section];
      cell.model = array[indexPath.row];
      cell.swtichvalue = ^(BOOL isOpen) {
           NSLog(@"isOpen--%d",isOpen);
          [self set_alarm_enable:isOpen];
      };
        switch (indexPath.section)
       {
           case 1:
           {
            
               if ([_PhotoOrCapture isEqualToString:NSLocalizedString(@"抓拍", nil)]) {
                   cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
                   
               }else{
                   cell.selectediMage.image = nil;
               }
               
           }
           break;
   
           case 2:
           {

               if ([_PhotoOrCapture isEqualToString:NSLocalizedString(@"录像", nil)]) {
                   cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
               }else{
                   cell.selectediMage.image = nil;
               }
               
               
               
           }
               break;
               
           case 3:
           {
               if(indexPath.row == 0) {
                   
                   if ([_videotime isEqualToString:NSLocalizedString(@"5 秒", nil)]) {
                       if (!selectedIndex) {
                            selectedIndex = indexPath;
                       }
                       cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
                       cell.detailLabel.text = nil;
                   }else{
                       cell.selectediMage.image = nil;
                       cell.detailLabel.text = nil;
                   }
                   
               }else if(indexPath.row == 1) {
                   
                   if ([_videotime isEqualToString:NSLocalizedString(@"10 1秒", nil)]) {
                       if (!selectedIndex) {
                            selectedIndex = indexPath;
                       }
                       cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
                   }else{
                       cell.selectediMage.image = nil;
                   }
                   
                   
               }else if( indexPath.row == 2) {
                   
                   if ([_videotime isEqualToString:NSLocalizedString(@"15 秒", nil)]) {
                       if (!selectedIndex) {
                            selectedIndex = indexPath;
                       }
                       cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
                   }else{
                       cell.selectediMage.image = nil;
                   }
               }
           }
                   break;
           default:
               break;
       }
   
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     SettingDetailTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.section == 1 && indexPath.row == 0) {
    
        if(isOpen){
            isOpen = NO;
        }
    
        if (isOpenVideo) {
            isOpenVideo = NO;
        }
        _PhotoOrCapture = NSLocalizedString(@"抓拍", nil);
      if (!_phoneNumber) {
          _phoneNumber = NSLocalizedString(@"1 张", nil);
      }
    }else if (indexPath.section == 2 && indexPath.row == 0){
        
        _PhotoOrCapture = NSLocalizedString(@"录像", nil);
        _phoneNumber = @"";
        isOpen = !isOpen;
        if (!isOpenVideo) {
             isOpenVideo = YES;
             cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
        }else{//反之关闭cell
             isOpenVideo = NO;
             cell.selectediMage.image = [UIImage imageNamed:@"settingselect.png"];
        }
    
        if (!_videotime) {
             _videotime = NSLocalizedString(@"5 秒", nil);
        }
        
   }else if (indexPath.section == 3 && indexPath.row == 0) {
         
         _PhotoOrCapture = NSLocalizedString(@"录像", nil);
         _videotime = NSLocalizedString(@"5 秒", nil);

     }else if(indexPath.section == 3 && indexPath.row == 1){
         
         _PhotoOrCapture = NSLocalizedString(@"录像", nil);
         _videotime = NSLocalizedString(@"10 秒", nil);
  
     }
     else if(indexPath.section == 3 && indexPath.row == 2){
          _PhotoOrCapture = NSLocalizedString(@"录像", nil);
          _videotime = NSLocalizedString(@"15 秒", nil);

     }

    
    [self.tableView reloadData];
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    return view;

}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


//自定义单元格样式
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cornerRadius = 8.f;
    // 设置cell的背景色为透明，如果不设置这个的话，则原来的背景色不会被覆盖
    cell.backgroundColor = UIColor.clearColor;
    // 创建一个shapeLayer
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef pathRef = CGPathCreateMutable();
    CGRect bounds = CGRectInset(cell.bounds,14, 0);
    
    
    if (indexPath.row == 0) {
        
        if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            
            CGPathMoveToPoint(pathRef, nil,CGRectGetMinX(bounds)+5, CGRectGetMinY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMinX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMinX(bounds), CGRectGetMinY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMinY(bounds), cornerRadius);
            CGPathCloseSubpath(pathRef);
        }else{
            // 初始起点为cell的左下角坐标
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
            // 起始坐标为左下角，设为p，（CGRectGetMinX(bounds), CGRectGetMinY(bounds)）为左上角的点，设为p1(x1,y1)，(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点，设为p2(x2,y2)。然后连接p1和p2为一条直线l1，连接初始点p到p1成一条直线l，则在两条直线相交处绘制弧度为r的圆角。
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
            CGPathCloseSubpath(pathRef);
        }
        
        
    } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
        
            // 初始起点为cell的左上角坐标
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            // 添加一条直线，终点坐标为右下角坐标点并放到路径中去
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
    } else {
        
            // 添加cell的rectangle信息到path中（不包括圆角）
            CGPathAddRect(pathRef, nil, bounds);
    }

            // 把已经绘制好的可变图像路径赋值给图层，然后图层根据这图像path进行图像渲染render
            layer.path = pathRef;
            backgroundLayer.path = pathRef;
            // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
            CFRelease(pathRef);
            // 按照shape layer的path填充颜色，类似于渲染render
            layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
            layer.fillColor = [UIColor whiteColor].CGColor;
            layer.strokeColor = [HexChangeRGB colorWithHexString:@"#e1e1e1"].CGColor;
            layer.lineWidth = 1.0;
            // view大小与cell一致
            UIView *roundView = [[UIView alloc] initWithFrame:bounds];
            // 添加自定义圆角后的图层到roundView中
            [roundView.layer insertSublayer:layer atIndex:0];
            roundView.backgroundColor = UIColor.clearColor;
            // cell的背景view
            cell.backgroundView = roundView;
            // 以上方法存在缺陷当点击cell时还是出现cell方形效果，因此还需要添加以下方法
            // 如果你 cell 已经取消选中状态的话,那以下方法是不需要的.
            UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
            backgroundLayer.fillColor = WXHColor(238, 238, 238, 1.0).CGColor;
            [selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
            selectedBackgroundView.backgroundColor = UIColor.clearColor;
            cell.selectedBackgroundView = selectedBackgroundView;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


#pragma mark - HeaderView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 1;
    }
}


#pragma mark - HeaderView
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}


- (void)setPhotoOrCapture:(NSString *)PhotoOrCapture
{
    _PhotoOrCapture = PhotoOrCapture;
    if ([PhotoOrCapture isEqualToString:NSLocalizedString(@"抓拍", nil)]) {
        isOpen = YES;
    }else{
        isOpen = NO;
    }
    
    if ([PhotoOrCapture isEqualToString:NSLocalizedString(@"录像", nil)]) {
        isOpenVideo = YES;
    }else{
        isOpenVideo = NO;
    }
    
}


- (void)set_alarm_enable:(BOOL)is_on
{
    {
        
        int format = is_on?1:0;
        [SVProgressHUD show];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       [dict setObject:[NSString stringWithFormat:@"%d",format] forKey:@"alarm_enable"];
 
        
       [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:_bid] errorHint:^(id errorData) {
           
           [SVProgressHUD dismiss];
            NSLog(@"alm_mod errorData -->%@",errorData);
           
       } deleteDic:dict isFavorite:YES result:^(id data) {
           NSLog(@"alm_mod data-->%@",data);
           [SVProgressHUD dismiss];
           if ([[data objectForKey:@"code"] intValue] == 0) {
               
               NSArray *r700_Array = [FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]];
               
               if (r700_Array.count) {
                   FBDevicesList *r700Info = [r700_Array firstObject];
                    r700Info.alarm_enable = format;
                   [r700Info bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                       dispatch_async(dispatch_get_main_queue(), ^{
                           if (isSuccess) {
                               NSLog(@"更新alm_mod成功");
                               [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Setup successful.", nil)];;
                             
                               [self reloadData:format];
                           }else{
                               NSLog(@"更新alm_mod不成功");
                           }
                       });
                   }];
                   
            
                   if (r700Info.status != 0) {
                        
                       NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                      [YKBusinessFramework equesSendData:Str];
                       
                       // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                       __block int timeout = 5; // 倒计时时间
                       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                       dispatch_source_t new_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                       dispatch_source_set_timer(new_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                       dispatch_source_set_event_handler(new_time, ^{
                           {
                               NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                              [YKBusinessFramework equesSendData:Str];
                               
                               timeout--;
                               if (timeout <= 0) {
                                  dispatch_source_cancel(new_time);
                               }
                           }
                           
                       });
                       dispatch_resume(new_time);
                       
                   }
               }
           }else{
               [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
           }
       }];
       
        return;
    }
}


- (void)saveToneAction:(UIButton*)sender
{

        int format = 0;
        int videotime = 5;
        if([_PhotoOrCapture isEqualToString:NSLocalizedString(@"抓拍", nil) ]){
            format = 1;
        }else{
            format = 2;
            if([_videotime isEqualToString:NSLocalizedString(@"5 秒", nil)]){
                videotime = 5;
            }else if ( [_videotime isEqualToString:NSLocalizedString(@"10 秒", nil)]){
                videotime = 10;
            }else{
                videotime = 15;
            }
        }
     
        [SVProgressHUD show];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
       [dict setObject:[NSString stringWithFormat:@"%d",format] forKey:@"alm_mod"];
       [dict setObject:[NSString stringWithFormat:@"%d",videotime] forKey:@"video_time"];
        
       [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:_bid] errorHint:^(id errorData) {
           
           [SVProgressHUD dismiss];
            NSLog(@"alm_mod errorData -->%@",errorData);
           
       } deleteDic:dict isFavorite:YES result:^(id data) {
           NSLog(@"alm_mod data-->%@",data);
           [SVProgressHUD dismiss];
           if ([[data objectForKey:@"code"] intValue] == 0) {
               
              
               NSArray *r700_Array = [FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]];
               
               if (r700_Array.count) {
                   FBDevicesList *r700Info = [r700_Array firstObject];
                    r700Info.alm_mod = format;
                    r700Info.video_time = videotime;
                   
                   
                   
                   [r700Info bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                       dispatch_async(dispatch_get_main_queue(), ^{
                           if (isSuccess) {
                               NSLog(@"更新alm_mod成功");
                               [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Setup successful.", nil)];
                               [self.navigationController popViewControllerAnimated:YES];
                           }else{
                               NSLog(@"更新alm_mod不成功");
                           }
                       });
                   }];
                   
            
                   if (r700Info.status != 0) {
                        
                       NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                      [YKBusinessFramework equesSendData:Str];
                       
                       // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                       __block int timeout = 5; // 倒计时时间
                       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                       dispatch_source_t new_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                       dispatch_source_set_timer(new_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                       dispatch_source_set_event_handler(new_time, ^{
                           {
                               NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                              [YKBusinessFramework equesSendData:Str];
                               
                               timeout--;
                               if (timeout <= 0) {
                                  dispatch_source_cancel(new_time);
                               }
                           }
                           
                       });
                       dispatch_resume(new_time);
                       
                   }
               }
           }else{
         
               [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed, please try again", nil)];
           }
       }];
       
        return;
    

}







@end
